package com.yunduo.common;

import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.entity.User;
import com.yunduo.handler.exceptionhandler.OperationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
 * @Author: fly
 * @create time: 2022/4/20 10:08
 * @description:  jwt工具类
 */
public class JwtUtils {
    //过期时间  1小时
    public static final long EXPIRE = 1000*60*60;
    //密钥
    public static final String APP_SECRET = "crazythursdayvmeFive";

    /**
     * 根据用户id和用户昵称生成token
     * @param id 用户id
     * @param nickname  用户昵称
     * @return
     */
    public static String getJwtToken(String id, String nickname,String password){
        String jwtToken = Jwts.builder()
                //设置头部信息---令牌类型、加密方式
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置主体信息
                .setSubject("yunduoUserInfo")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))                 //设置过期时间
                .claim("id", id)
                .claim("name", nickname)
                .claim("password",password)
                //设置签名 进行编码
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return jwtToken;
    }


    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = getTokenStringRequest(request);
            if(StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            throw new OperationException(UserCode.USER_LOGIN_TIMEOUT.getCode(),UserCode.USER_LOGIN_TIMEOUT.getInfo());
        }
        return true;
    }


    /**
     * 根据token获取信息
     * @param request
     * @return
     */
    public static User getDataByJwtToken(HttpServletRequest request) {
        String jwtToken = getTokenStringRequest(request);
        //解析token字符串
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        //获取token的主体信息
        Claims claims = claimsJws.getBody();
        User user = new User().setId((String)claims.get("id")).
                setName((String)claims.get("name")).
                setPassword((String)claims.get("password"));
        return user;
    }

    private static String getTokenStringRequest(HttpServletRequest request){
        //获取请求中token值
        String headJwtToken = request.getHeader("Authorization");
        String paramJwtToken = request.getParameter("Authorization");
        if(StringUtils.isEmpty(headJwtToken) && StringUtils.isEmpty(paramJwtToken) ) {
            return null;
        }
        if(StringUtils.isEmpty(headJwtToken)){
            return paramJwtToken;
        } else {
            return headJwtToken;
        }
    }
}
